import React, { Component } from 'react';
import { Modal, Input, Cascader, message } from 'antd';
import PropTypes from 'prop-types';
import cn from 'classnames';
import { ORGANIZATION_RE } from '@util/constants';
import { addOrganization, updateOrganization } from '@api/organization';
import _ from 'lodash';
import './index.less';

const MODE_MAP = {
  add: '创建',
  edit: '编辑'
};

class AddEditModal extends Component {
  static propTypes = {
    mode: PropTypes.string,
    cascaderTree: PropTypes.array,
    currentOrg: PropTypes.object,
    level: PropTypes.number,
    levelCN: PropTypes.string,
    visible: PropTypes.bool,
    onCancel: PropTypes.func,
    onOk: PropTypes.func
  };

  static treePruning = (rawTree = [], rawPaths = [], id) => {
    if (!id) {
      return _.cloneDeep(rawTree);
    }
    let tree = _.cloneDeep(rawTree),
      paths = _.cloneDeep(rawPaths);
    let tmpChildren = tree;
    while (tmpChildren.length && paths.length) {
      let current = paths.shift();
      let tmpParent = _.find(tmpChildren, i => _.get(i, '_id') === current);
      tmpChildren = _.get(tmpParent, 'children', []);
    }
    let currentIndex = _.findIndex(tmpChildren, i => _.get(i, '_id') === id);
    tmpChildren.splice(currentIndex, 1);
    return tree;
  };

  static getStateFromProps = props => {
    let {
      paths: rawPaths = [],
      // eslint-disable-next-line
      _id: id = '',
      // eslint-disable-next-line
      parent_oid: parentId = '',
      name = ''
    } = _.get(props, 'currentOrg', {});
    let rawCascaderTree = _.get(props, 'cascaderTree', []);
    let cascaderTree = AddEditModal.treePruning(rawCascaderTree, rawPaths, id);
    return {
      id: id,
      name,
      parentId,
      paths: rawPaths,
      cascaderTree,
      nameError: '',
      confirmLoading: false
    };
  };
  constructor(props) {
    super(props);
    this.state = {
      ...AddEditModal.getStateFromProps(props)
    };
  }

  // eslint-disable-next-line
  UNSAFE_componentWillReceiveProps(nextProps) {
    if (!this.props.visible && nextProps.visible) {
      this.setState({
        ...AddEditModal.getStateFromProps(nextProps)
      });
    }
  }

  onNameChange = e => {
    let name = e.target.value;
    let body = { name, nameError: '' };
    if (!ORGANIZATION_RE.test(name)) {
      body.nameError = '请输入正确格式的部门名称';
    }
    this.setState(body);
  };
  onOk = () => {
    const { id, parentId, name, nameError } = this.state;
    if (nameError) {
      return;
    }
    if (!name) {
      this.setState({ nameError: '请填写部门名称' });
      return;
    }
    const { mode = 'add', levelCN = '一' } = this.props;
    let todo = null,
      body = { name };
    if (mode === 'add') {
      todo = addOrganization;
      body.name = name;
      if (parentId) {
        body['parent_id'] = parentId;
      }
    } else {
      todo = updateOrganization;
      body['id'] = id;
      if (parentId) {
        body['parent_id'] = parentId;
      } else {
        body['level'] = 1;
      }
    }
    this.setState({ confirmLoading: true });
    todo(body)
      .then(res => {
        if (_.get(res, 'data.data.organization._id')) {
          message.success(`${MODE_MAP[mode]}${levelCN}级部门成功`);
          this.props.onOk();
        } else {
          message.error(`${MODE_MAP[mode]}${levelCN}级部门失败`);
        }
      })
      .catch(err => {
        if (err && err.message) {
          message.error(err.message);
        } else {
          message.error(`${MODE_MAP[mode]}${levelCN}级部门失败`);
        }
      })
      .finally(() => {
        this.setState({ confirmLoading: false });
      });
  };
  onParentChange = (parents = []) => {
    let parentId = parents[parents.length - 1],
      update = { paths: parents, parentId };
    this.setState(update);
  };

  render() {
    const { name, nameError, confirmLoading, paths, cascaderTree } = this.state;
    const { mode = 'add', visible, level = 1, levelCN = '一' } = this.props;
    const disableBelong = level === 1 && mode === 'add';
    return (
      <Modal
        maskClosable={false}
        visible={visible}
        title={`${MODE_MAP[mode]}${levelCN}级部门`}
        onOk={this.onOk}
        onCancel={this.props.onCancel}
        confirmLoading={confirmLoading}
        className={cn(
          'no-header-bottom-lines',
          'bottom-center',
          'padding-24',
          'org-c-add-edit-modal'
        )}
      >
        <div className="item">
          <label>部门名称</label>
          <Input
            className="item-value"
            placeholder="请输入数字、中文或英文、不超过 16 个字符"
            value={name}
            onChange={this.onNameChange}
          />
        </div>
        {nameError && <p className="name-error">{nameError}</p>}

        {!disableBelong && (
          <div className="item">
            <label>所属部门</label>
            <Cascader
              value={paths}
              options={cascaderTree}
              className="item-value"
              changeOnSelect
              onChange={this.onParentChange}
              placeholder="选择所属部门"
              fieldNames={{ label: 'name', value: '_id', children: 'children' }}
            />
          </div>
        )}
      </Modal>
    );
  }
}

export default AddEditModal;
